package com.test.mchelepesa.util_rice.data.util

import android.content.Context
import android.content.pm.PackageManager
import android.util.Base64
import java.io.ByteArrayOutputStream
import java.nio.charset.StandardCharsets
import java.util.zip.GZIPOutputStream
import kotlin.math.max

fun Context.checkPermissionsGranted(list: List<String>): Boolean {
    val notGranted = list.any {
        checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED
    }
    return !notGranted
}

fun String?.safe(): String {
    if (this.isNullOrBlank()) return ""
    return this
}

fun Int.safeZero(): Int {
    return max(this, 0)
}

fun String?.safeInt(default: Int = 0): Int = this?.toIntOrNull() ?: default

fun String?.safeLong(): Long {
    if (this.isNullOrBlank()) return 0L
    return try {
        this.toLong()
    } catch (e: Exception) {
        0L
    }
}

fun String.gzipString(): String {
    if (isBlank()) return ""

    return try {
        val utf8Bytes = this.toByteArray(StandardCharsets.UTF_8)
        ByteArrayOutputStream().use { outputStream ->
            GZIPOutputStream(outputStream).apply {
                write(utf8Bytes)
                close()
            }
            Base64.encodeToString(
                outputStream.toByteArray(),
                Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING
            )
        }
    } catch (e: Exception) {
        ""
    }
}


